import 'dart:async';

import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:yysk_app/model/pay_model/bank_card_list_model.dart';
import 'package:yysk_app/model/pay_model/payment_order_pay_model.dart';
import 'package:yysk_app/model/pay_model/query_rechange_rrices_model.dart';
import 'package:yysk_app/model/pay_model/user_register_query_model.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/login/login_controller.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/confirm_payment/confirm_payment_controller.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/enterprise_auth_zhifu/my_webview_zhifu_pay.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/wallet/wallet_page.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/js_tool.dart';

class BankCardInfo {
  final String bankName;
  final String tailNo;
  BankCardInfo(this.bankName, this.tailNo);
}

class InvestmoneyController extends GetxController {
  // var availableAmount = 0.0.obs;
  var selectedBank = Rxn<BankCardInfo>();
  var amountController = TextEditingController();
  var canWithdraw = false.obs;

  final ScrollController scrollController = ScrollController();
  final detail = '0.00'.obs; //可提现
  var type = '1'.obs; //1个人，2企业,3个体工商户
  var channel = 'DIN_PAY'.obs; //支付类型 //HUIFU汇付
  final rechangePricesDetail = Rx<QueryRechangePricesModel?>(null);
  final payList = RxList<CashierRouteData?>([]); //支付列表

  var payCards = RxList<BankCardListModel>();
  final selsectInfo = Rx<BankCardListModel?>(null);
  final getPrice = '0'.obs;
  final isRefresh = true.obs;
  final arr = RxList([]);
  Timer? timer;
  var choosePrice = ''.obs;
  @override
  void onInit() {
    super.onInit();
    type.value = Get.parameters['type'] ?? Get.arguments['type'];
    channel.value = Get.parameters['channel'] ?? Get.arguments['channel'];
    amountController.text = '';
    getQueryRechangePrices();
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
  }

  Future getQueryRechangePrices() async {
    await http.netFetch<QueryRechangePricesModel>(
      PayUrl.queryRechangePrices,
      method: Method.post,
      params: {},
      success: (res) {
        rechangePricesDetail.value = res.data;
        payList.value = res.data!.cashierRoute!.data!;
      },
    );
  }

  void chooseTxt(txt) {
    choosePrice.value = txt;
    amountController.text = txt;
    // double.parse(choosePrice.value ?? '0').toStringAsFixed(2);
  }

  //去实名
  toSm({required BuildContext context}) async {
    await showConfirmDialog(
      context: context,
      message: '请先完成实名认证',
      messages: [],
      fontSize: 16,
      actions: [
        ActionModel(
          label: '取消',
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
          onPressed: () {},
        ),
        ActionModel(
          label: '立即认证',
          onPressed: () {
            Get.toNamed(SettingRealNameAuthPage.path);
          },
        ),
      ],
    );
  }

  //是否开通钱包
  Future<dynamic> isOpenWallet({bool isAddBank = false}) async {
    try {
      await http.netFetch<UserRegisterQueryModel>(
        PayUrl.registerQuery,
        method: Method.post,
        params: {'plat': 'USER', 'channel': channel.value},
        success: (result) {
          if (result.code == 200 && result.data?.status == true) {
            deposit();
          } else {
            showConfirmDialog(
              context: Get.context!,
              message: '请先开通钱包',
              messages: ['开通后请前往藏品待支付订单中支付'],
              actions: [
                ActionModel(
                  label: '取消',
                  onPressed: () {},
                  colorStart: AppColors.backgroundColorGreyF8,
                  colorEnd: AppColors.backgroundColorGreyF8,
                  fontColor: AppColors.fontColor,
                ),
                ActionModel(
                  label: '前往开通',
                  onPressed: () {
                    try {
                      Get.until((route) => Get.currentRoute == MainPage.path);
                    } catch (e) {
                      Get.offAllNamed(MainPage.path);
                    }
                    Get.toNamed(WalletPage.path);
                  },
                ),
              ],
            );
          }
        },
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  //充值
  Future deposit() async {
    String userToken = '';
    try {
      ConfirmPaymentController confirmController = Get.find();
      userToken = confirmController.token.value;
    } catch (e) {
      userToken =
          HiCache.getInstance().get(LoginController.boardingPassToken) ??
          getToken();
    }
    await http.netFetch<PaymentOrderPayModel>(
      PayUrl.paymentDeposit,
      params: {
        'payAmt': amountController.text,
        'channel': 'DIN_PAY',
        "payMethod": 'DIN_PAY',
        'userToken': userToken,
      },
      success: (result) {
        if (result.code == 200) {
          amountController.text = '';
          Get.toNamed(
            '${MyWebViewZhifuPayPage.path}?url=${Uri.encodeComponent(result.data?.payUrl.toString() ?? '')}&outTradeNo=${result.data?.outTradeNo}',
            arguments: {
              'url': Uri.encodeComponent(result.data?.payUrl.toString() ?? ''),
              'outTradeNo': result.data?.outTradeNo,
            },
          );
        }
      },
    );
  }
}
